package com.neo.push.client.handler;

import com.neo.push.core.PingMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by lock on 17-7-28.
 *
 * 前端的心跳触发
 *
 */
public class ClientHearBeatTrigger extends IdleStateHandler {

    /**
     * 当间隔多少秒没有与服务器进行通信后，则发送心跳包
     *
     * @param triggerSeconds    间隔
     */
    public ClientHearBeatTrigger(int triggerSeconds) {
        super(0, triggerSeconds, 0);
    }


    /**
     * 如果连接有超时现象
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if(evt.state() == IdleState.WRITER_IDLE){
            ctx.writeAndFlush(new PingMessage());
        }
    }
}
